<template>
   <!-- alt键 + 点击 跳转到文档页面 -->
   <el-card shadow="hover">
    <template #header>
      <el-button type="primary" icon="el-icon-plus" @click="showDialog({tmName:'',logoUrl:''})">添加</el-button>
    </template>

    <el-table :data="list" border v-loading="loading" style="width: 100%">
      <el-table-column 
      label="序号" 
      type="index" 
      width="80" 
      align="center"
      prop="date"/>
      <el-table-column label="品牌名称" prop="tmName"/>
      <el-table-column label="品牌LOGO">
        <template v-slot="{row}"> <!-- row: 当前行数据对象 -->
          <el-image :src="row.logoUrl" style="width:100px;height: 60px;"></el-image>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template v-slot="{row}">
          <el-button type="warning" size="small" icon="el-icon-edit" @click="showDialog(row)"></el-button>
          <el-popconfirm
                  :title="`你确定要删除${row.tmName}吗？`"
                  @onConfirm="onConfirm(row.id)"
                >
                <el-button type="danger" size="small" icon="el-icon-delete"  slot="reference"></el-button>
        </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[1, 3, 6]"
      :page-size="limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
     <!-- isdialog区域 -->
    <el-dialog :visible.sync="isShowDialog" :title="trademarkForm.id ? '修改品牌' : '添加品牌'">
      <el-form  label-width="140px" :model="trademarkForm" :rules ="rules" ref="formRef">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
          autocomplete="off" 
          placeholder="请输入品牌名称"
          v-model="trademarkForm.tmName"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- 
            action: 处理图片上传请求的url
                  不能直接写目标地址  => 跨域了
                  必须写一个带代理前缀路径的路径
            show-file-list: false  单个图片
           -->
           <el-upload
              class="avatar-uploader"
              :action="`${BASE_UPLOAD}/admin/product/fileUpload`"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="trademarkForm.logoUrl" :src="trademarkForm.logoUrl" class="avatar">
              <i v-else class="el-icon-plus el-upload avatar-uploader-icon"></i>
              <template #tip>
                <div class="el-upload__tip">只能上传jpg/png文件，且不超过50kb</div>
            </template>
            </el-upload>
          </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isShowDialog = false">取消</el-button>
          <el-button type="primary" @click="confirm" >确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import { getTrademarkPageListApi,saveTrademarkApi2,updateTrademarkApi,removeTrademarkApi } from '@/api/product/trademark'

  export default {
    name:'Trademark',
    data(){
      return {
        list : [],
        currentPage:1,
        total:0,
        limit:3,
        loading:false,
        isShowDialog:false,
        //图片代理
        BASE_UPLOAD:process.env.VUE_APP_BASE_API, 
        //收集品牌表单数据
        trademarkForm: {
        tmName: '',
        logoUrl: ''
      },
       //收集品牌表单数据
       rules:{
        tmName:[
          {required:true,message:'品牌名称是必须在3-6位', trigger: 'change' }//change是失去焦点
         ],
         logoUrl:[
         {required: true, message: '品牌LOGO是必须的'}
         ]
      }
      }
    },
    methods: {
        // 请求函数渲染列表
     async getList(){
        // 显示loading效果
        this.loading = true
        // 发请求
        const result = await getTrademarkPageListApi(this.currentPage,this.limit)
      // 请求成功后更新数据
        this.total = result.data.total
        this.list= result.data.records
        // 隐藏loading
        this.loading = false        
      },
      handleSizeChange(val){
        this.limit = val
      },
      handleCurrentChange(val){
        this.currentPage = val
      },
      showDialog(trademark){
        // 显示dialog
          this.isShowDialog = true,
        // 如果trademark有值, 更新trademarkForm显示到表单中
        // if (trademark) {  // 点击添加时, 传入一个空的trademark对象
          this.trademarkForm.id = trademark.id,
          this.trademarkForm.tmName = trademark.tmName,
          this.trademarkForm.logoUrl = trademark.logoUrl
        // }
      },
      //图片上传成功后的回调
      handleAvatarSuccess(res) {
        this.trademarkForm.logoUrl = res.data
      },
       //图片上传之前的回调
      beforeAvatarUpload(rawFile) {
        if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
             this.$message.error('图片必须是jpg或png')
              return false
            } else if (rawFile.size / 1024  > 50) {
              this.$meessage.error('图片不能超过50KB!')
              return false
            }
            return true
      },
       //确认请求添加或更新
       confirm (){
            this.$refs.formRef.validate(async() =>{
              if (this.trademarkForm.id) {
                  await updateTrademarkApi(this.trademarkForm)
                } else {
                  await saveTrademarkApi2(this.trademarkForm)
                }
                // 成功之后, 隐藏dialog, 重新获取列表显示, 提示添加或更新成功
                this.isShowDialog = false
                this.getList()
                this.$message.success(`${this.trademarkForm.id ? '更新' : '添加'}成功!`)
                  })
          },
     
      //删除请求
      async onConfirm(id){
        await removeTrademarkApi(id)
        this.$message.success(`删除成功!`)
        this.getList()
      }
    },
    mounted() {
    this.getList()
    },
    watch:{
      currentPage(){
        this.getList()
      },
      limit(){
        this.getList()
      }
    }
  }

</script>

<style lang="scss" scoped>
     .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

</style>